import PageCommon from "@/components/PageCommon";
import { getUserList } from "@/services/user";
import { PlusOutlined } from "@ant-design/icons";
import type { ActionType, ProColumns } from "@ant-design/pro-components";
import { ProTable } from "@ant-design/pro-components";
import { history } from "@umijs/max";
import { Button, message, Popconfirm, Space } from "antd";
import { useRef, useState } from "react";

const UseList = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const columns: ProColumns<Types.User.IUserInfo>[] = [
    {
      title: "ID",
      dataIndex: "id"
    },
    {
      title: "名字",
      dataIndex: "name"
    },
    {
      title: "创建时间",
      dataIndex: "create_time",
      hideInSearch: true
    },
    {
      title: "操作",
      dataIndex: "filter",
      hideInSearch: true,
      width: 150,
      fixed: "right",
      render: (_, record) => {
        return (
          <Space size={12}>
            <a onClick={() => record?.id && history.push(`/users/list/${record?.id}`)}>编辑</a>
            <a onClick={() => record?.id && history.push(`/users/detail/${record?.id}`)}>详情</a>
            <Popconfirm
              title="确定是否删除？"
              onConfirm={async () => {
                message.success("删除成功！");
                actionRef.current?.reload();
              }}
            >
              <Button
                type="link"
                style={{
                  color: "red",
                  padding: 0
                }}
              >
                删除
              </Button>
            </Popconfirm>
          </Space>
        );
      }
    }
  ];

  return (
    <PageCommon>
      <ProTable<Types.User.IUserInfo>
        actionRef={actionRef}
        rowKey="id"
        request={async () => {
          let resp = await getUserList();
          if (resp.code === 1) {
            return {
              success: resp.code === 1,
              data: resp.data
            };
          }
          return {};
        }}
        columns={columns}
        toolbar={{
          settings: []
        }}
        scroll={{
          x: 1500
        }}
        headerTitle={[
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              history.push(`/users/list/new`);
            }}
          >
            <PlusOutlined /> 新增用户
          </Button>
        ]}
        rowSelection={{
          selectedRowKeys,
          onChange: (key) => {
            setSelectedRowKeys(key);
          }
        }}
        tableAlertRender={({ selectedRowKeys, selectedRows }) => {
          console.log(selectedRowKeys, selectedRows);
          return (
            <Space size={24}>
              <span>已选 {selectedRowKeys.length} 项</span>
            </Space>
          );
        }}
      />
    </PageCommon>
  );
};

export default UseList;
